#include "wvstreams/wvstringlist.h"
#include "wvstreams/wvunixsocket.h"

int main(int argc, char **argv)
{
    if (argc <= 1)
    {
	wverr->print("Usage: %s <cmd> [parameters...]\n"
		     " Ask weaver to run a command via /tmp/rcmd.\n"
		     " (Try '%s help')\n", argv[0], argv[0]);
	return 1;
    }
    
    WvStringList l;
    for (int i = 1; i < argc; i++)
	l.append(argv[i]);
    WvString cmd(l.join(" "));
    
    WvUnixConn s("/tmp/rcmd");
    const char *line;
    
    for (;;)
    {
	line = s.getline(-1);
	if (!line)
	{
	    if (s.geterr())
		wverr->print("%s: /tmp/rcmd: %s\n", argv[0], s.errstr());
	    else
		wverr->print("%s: disconnected suddenly??", argv[0]);
	    return 2;
	}
	if (!strncmp(line, "* ", 2))
	    continue;
	else if (!strncmp(line, "HELLO ", 6))
	    break;
	else
	{
	    wverr->print("%s: expected HELLO, got: '%s'\n",
			 argv[0], line);
	    return 3;
	}
    }
    
    s.print("%s\nquit\n", cmd);
    
    bool echo = true;
    while ((line = s.getline(-1)) != NULL)
    {
	if (!strncmp(line, "- ", 2))
	{
	    if (echo)
		wvout->print("%s\n", line + 2);
	}
	else if (!strncmp(line, "OK ", 3))
	{
	    if (echo)
		wvout->print("%s\n", line + 3);
	    echo = false;
	    break;
	}
	else if (!strncmp(line, "ERROR ", 6))
	{
	    if (echo)
	    {
		wvout->print("%s\n", line + 6);
		return 4;
	    }
	}
    }
    
    return 0;
}
